package com.taiyuan.zfmvp.JUC.lock;

import com.taiyuan.zfmvp.shejimoshi.single.type1.SingletonTest01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @param
 * @Author: zhoufang@si-tech.com.cn
 * @Descriiption: 线程间通信  wait notify
 * @Date 2022/10/3
 * @return
 */

class share{

    private int number = 0;

    private Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public   void incr(){
        lock.lock();
        try {
            while(number != 0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"::"+number);
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    public   void decr(){
        lock.lock();

        try {
            if(number != 1){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"::"+number);
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

}

public class ThreadDemo2 {

    public static void main(String[] args) {
        share s = new share();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 10 ; i++) {
                    try {
                        s.incr();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        },"a").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 10 ; i++) {
                    try {
                        s.decr();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        },"b").start();
    }

}
